﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using SageKing.AspNetCore.Extensions;
using SageKing.Core.Contracts;

namespace SageKing.AspNetCore;

/// <summary>
/// 自定义模型验证过滤器，返回统一结果SageKingResult
///  // 在Program.cs中配置 
///       builder.Services.Configure<ApiBehaviorOptions>(options =>
///       {
///           // 禁用默认行为，使用自定义的模型验证过滤器 ValidateModelSageKingResultAttribute
///           options.SuppressModelStateInvalidFilter = true;
///       });
///       builder.Services.AddControllers(options =>
///       {
///           options.Filters.Add<ValidateModelSageKingResultAttribute>();//注册全局过滤器
///       });
/// </summary>
public class ValidateModelSageKingResultAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            var result = new SageKingResult<IDictionary<string, string[]>>();
            var errors = context.ModelState.GetAllErrors() ?? new Dictionary<string, string[]>();

            // 设置结果，短路当前请求
            context.Result= new BadRequestObjectResult(result.BadRequest(errors, "请求参数错误"));
        }
    }
}